package top.yrlby.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import top.yrlby.common.BaseContext;
import top.yrlby.common.CustomException;
import top.yrlby.pojo.*;
import top.yrlby.dao.OrdersMapper;
import top.yrlby.service.*;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;

/**
 * <p>
 * 订单表 服务实现类
 * </p>
 *
 * @author baiyang
 * @since 2022-09-05
 */
@Service
public class OrdersServiceImpl extends ServiceImpl<OrdersMapper, Orders> implements OrdersService {

    @Autowired
    private ShoppingCartService shoppingCartService;

    @Autowired
    private UserService userService;

    @Autowired
    private AddressBookService addressBookService;

    @Autowired
    private OrderDetailService orderDetailService;
    @Override
    public void submit(Orders orders) {
        Long currentId = BaseContext.getCurrentId();

        LambdaQueryWrapper<ShoppingCart> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ShoppingCart::getUserId,currentId);
        List<ShoppingCart> shoppingCarts = shoppingCartService.list(queryWrapper);

        if(CollectionUtils.isEmpty(shoppingCarts)){
            throw new CustomException("购物车为空，不能下单");
        }

        User user = userService.getById(currentId);

        Long addressBookId = orders.getAddressBookId();
        AddressBook byId = addressBookService.getById(addressBookId);
        if(byId == null){
            throw new CustomException("用户地址信息有误，不能下单！");
        }

        long id = IdWorker.getId();

        AtomicInteger atomicInteger = new AtomicInteger(0);

        List<OrderDetail> orderDetails = shoppingCarts.stream().map(item->{

            OrderDetail orderDetail = new OrderDetail();
            orderDetail.setOrderId(id);

            BeanUtils.copyProperties(item,orderDetail);

            atomicInteger.addAndGet(item.getAmount().multiply(new BigDecimal(item.getNumber())).intValue());
            return orderDetail;
        }).collect(Collectors.toList());

        orders.setId(id);
        orders.setOrderTime(LocalDateTime.now());
        orders.setCheckoutTime(LocalDateTime.now());
        orders.setStatus(2);
        orders.setAmount(new BigDecimal(atomicInteger.get()));//总金额
        orders.setUserId(id);
        //订单编号：20221215000001
        orders.setNumber(String.valueOf(id));
        orders.setUserName(user.getPhone());
        orders.setConsignee(byId.getConsignee());
        orders.setPhone(byId.getPhone());
        orders.setAddress(byId.getDetail());
        this.save(orders); //insert orders

        //4.向订单明细表插入数据，多条数据 insert order_detail
        orderDetailService.saveBatch(orderDetails);

        //5.清空购物车数据
        shoppingCartService.remove(queryWrapper);

    }
}
